define(function (require, exports) {
  exports.ready = function (hashCode, data, cite) {
    yufp.custom.vue({
      el: cite.el,
      data: function () {
        var _self = this;
        return {
          formdata1: {},
          urls: {
            index: backend.workflowService + '/api/nwfflow/',
            show: backend.workflowService + '/api/nwfflow/flow',
            create: backend.workflowService + '/api/nwfflow/',
            update: backend.workflowService + '/api/nwfflow/update/',
            batchdelete: backend.workflowService + '/api/nwfflow/delete/',
            state: backend.workflowService + '/api/nwfflow/state/',
            exportFlow: backend.workflowService + '/api/nwfflow/exportFlow/',
            importFlow: backend.workflowService + '/api/nwfflow/importFlow/'
          },
          commonparams: {
            systemId: yufp.session.logicSys.id,
            CurrentuserId: yufp.session.user.loginCode
          },

          tableColumns: [{
            label: '流程名称',
            prop: 'flowName',
            resizable: true
          },
          {
            label: '流程标识',
            prop: 'flowSign',
            resizable: true,
            hidden: false
          },
          {
            label: '流程ID',
            prop: 'flowId',
            resizable: true
          },
          {
            label: '流程创建者',
            prop: 'flowAdmin',
            resizable: true,
            hidden: false
          },
          {
            label: '流程修改时间',
            prop: 'startTime',
            width: '180px',
            resizable: true,
            hidden: false
          },
          {
            label: '系统id',
            prop: 'systemId',
            resizable: true,
            hidden: true
          },
          {
            label: '流程图状态',
            prop: 'flowState',
            resizable: true,
            template: function () {
              return '<template scope="scope">\
              <yu-tag type="success" v-if="scope.row.flowState == \'R\' ">启用</yu-tag>\
              <yu-tag type="warning" v-if="scope.row.flowState == \'B\' ">编辑中</yu-tag>\
              <yu-tag type="danger" v-if="scope.row.flowState == \'E\' ">停用</yu-tag>\
              </template>';
            }
          },
          {
            label: '流程图内容',
            prop: 'flowContent',
            resizable: true,
            hidden: true
          },
          {
            label: '管理员机构id',
            prop: 'orgId',
            resizable: true,
            hidden: true
          },
          {
            label: '操作',
            template: function () {
              return '<template scope="scope">\
              <yu-button-drop :show-length=2 type="text">\
                <el-button type="text" @click="$emit(\'custom-row-op\',scope,\'info\')" >查看</el-button>\
                <el-button type="text" @click="$emit(\'custom-row-op\',scope,\'edit\')" >编辑</el-button>\
                <el-button type="text" @click="$emit(\'custom-row-op\',scope,\'stop\')" v-if="scope.row.flowState==\'R\'">停用</el-button>\
                <el-button type="text" @click="$emit(\'custom-row-op\',scope,\'start\')" v-if="scope.row.flowState==\'E\'||scope.row.flowState == \'B\'">启用</el-button>\
              </yu-button-drop>\
              </template>';
            }
          }
          ],
          params: {},
          updateFields: [{
            columnCount: 2,
            fields: [{
              label: '流程名称',
              field: 'flowName',
              type: 'input',
              rules: [{
                required: true,
                message: '必填项'
              }]
            }]
          }],
          updateButtons: [
            {
              label: '保存',
              type: 'primary',
              hidden: false,
              click: function (model) {
                var validate = false;
                _self.$refs.reform.validate(function (valid) {
                  validate = valid;
                });
                if (!validate) {
                  return;
                }
                // 特殊字符校验
                var reg = new RegExp('[`~!@#%$^&*()=|{}\':;\',\\[\\].<>/?~！@#￥……&*（）|{}【】‘；：”“\'。，、？]');
                if (model.flowName && reg.test(model.flowName)) {
                  _self.$message({ message: '包含特殊字符', type: 'warning' });
                  return;
                }
                var formUrl = _self.urls.update;
                yufp.service.request({
                  method: 'POST',
                  url: formUrl,
                  data: model,
                  callback: function (code, message, response) {
                    if (response.code == 0) {
                      _self.$refs.reftable.remoteData();
                      _self.$message({ duration: 4000, message: '修改成功!', type: 'success' });
                      _self.updatedialogVisible = false;
                      _self.$nextTick(function () {
                        _self.$refs.reform.resetFields();
                      });
                    }
                  }
                });
              }
            },
            {
              label: '取消',
              hidden: false,
              click: function (model) {
                _self.updatedialogVisible = false;
              }
            }
          ],
          baseParams: {
            condition: JSON.stringify({
              systemId: 'cmis'
            })
          },
          editForm: {
            newflowId: '',
            newflowName: ''
          },
          height: yufp.frame.size().height - 103,
          newdialogVisible: false,
          updatedialogVisible: false,
          formDisabled: false,
          viewType: 'ADD',
          startTime: '',
          Switch: [],
          trackDialogVisible: false,
          nwfTrackPage: 'nwfTrackPage',
          viewTitle: yufp.lookup.find('CRUD_TYPE', false),
          headers: {'Authorization': 'Bearer ' + yufp.service.getToken()}
        };
      },
      computed: {
        action: function () {
          // 获取全路径
          return yufp.service.getUrl({ url: this.urls.importFlow });
        }
      },
      methods: {
        switchStatus: function (viewType) {
          var _self = this;
          _self.viewType = viewType;
          if (viewType == 'EDIT') {
            _self.updatedialogVisible = true;
          } else if (viewType == 'ADD') {
            _self.newdialogVisible = true;
          }
        },
        addFn: function () { // 新增
          var _self = this;
          _self.switchStatus('ADD'); // 切换面板状态
        },
        modifyFn: function () { // 修改
          if (this.$refs.reftable.selections.length != 1) {
            this.$message({
              duration: 4000,
              message: '请先选择一条记录',
              type: 'warning'
            });
            return;
          }
          this.switchStatus('EDIT');
          this.$nextTick(function () {
            var obj = this.$refs.reftable.selections[0];
            yufp.extend(this.$refs.reform.formModel, obj);
          });
        },
        customRowOp: function (scope, op) {
          // 当前行号：scope.$index
          // 当前行数据：scope.row
          // 当前列对象：scope.column
          // this.$alert('你现在正在操作：' + op + '当前行ID值为：' + scope.row.flowId, '提示');
          var _self = this;
          var state = '';
          if (op == 'edit') {
            // 启用状态无法编辑
            if (scope.row.flowState == 'R') {
              _self.$message({ duration: 4000, message: '启用状态无法编辑', type: 'warning' });
              return;
            }
            _self.viewType = 'EDIT'; // 切换面板状态
            _self.$nextTick(function () {
              // 打开工作流编辑
              state = 'B';
              _self.changeState(scope.row, state);
              _self.openWorkFlow(scope.row);
            });
          } else if (op == 'stop') { // 停用
            state = 'E';
            _self.changeState(scope.row, state);
          } else if (op == 'start') { // 启用
            state = 'R';
            _self.changeState(scope.row, state);
          } else if (op == 'info') { // 查看
            _self.infoFn(scope.row);
          }
        },
        infoFn:function(row){
			var _this = this;
			var params = {
			  flowId: row.flowId,
			  returnBackFuncId: cite.id,
			  returnBackRootId: cite.rootId
			};
			yufp.service.request({
			  method: 'GET',
			  url: _this.urls.show,
			  data: params,
			  callback: function (code, message, response) {
			    if (response.code == 0) {
			      if (response.data != null) {
					if(response.data.flowContent == null) {
					    _this.$message({ duration: 4000, message: '流程图内容为空', type: 'warning' });
					  }
					_this.trackDialogVisible = true;
			        var flowId = row.flowId;
			        var routeId = 'router_workflow_' + flowId;
			        var url = 'pages/workflow/studio/nwflist/workFlow/workFlow';
			        // 判断路由是否已经存在
			        var r = yufp.router.getRoute(routeId);
			        if (!r || !r.html) {
			          yufp.router.addRoute(routeId, {
			            html: url + '.html',
			            js: url + '.js'
			          });
			        }
			        _this.$nextTick(function () {
			          try {
			            yufp.router.to(routeId, params, _this.nwfTrackPage);
			          } catch (e) { }
			        });
			      }else {
			        _this.$message({ duration: 4000, message: '流程图内容不存在', type: 'warning' });
			      }
			    } else {
			      _this.$message({ duration: 4000, message: '获取数据异常:' + response.message.substring(0, 100), type: 'error' });
			    }
			  }
			});
		},
        openWorkFlow: function (data) {
          // 重新打开节点页面
          var customKey = 'custom_flow_' + data.flowId;
          var routeId = 'router_flow_' + data.flowId;
          var url = 'pages/workflow/studio/nwflist/jWorkflow/jWorkflow';
          // 判断路由是否已经存在
          var r = yufp.router.getRoute(routeId);
          if (!r || !r.html) {
            yufp.router.addRoute(routeId, {
              html: url + '.html',
              js: url + '.js'
            });
          }

          // 将数据中的flowContent字段去掉,该值在子页面查询了
          delete data.flowContent;
          yufp.frame.addTab({
            id: routeId, // 菜单功能ID（路由ID）
            key: customKey, // 自定义唯一页签key,请统一使用custom_前缀开头
            title: data.flowName + '图', // 页签名称
            data: data // 传递的业务数据，可选配置
          });
        },
        changeState: function (row, state) { // 切换流程状态
          var _self = this;
          var param = {
            flowId: row.flowId,
            flowState: state,
            flowSign: row.flowSign,
            startTime: row.startTime
          };
          yufp.service.request({
            method: 'POST',
            url: _self.urls.state,
            data: param,
            callback: function (code, message, response) {
              if (response.data) {
                _self.$refs.reftable.remoteData();
                if (state == 'start') {
                  _self.$message('流程已成功启用!');
                } else if (state == 'stop') {
                  _self.$message('流程已停用!');
                }
              } else {
                _self.$message({ duration: 4000, message: '流程图操作异常:' + response.message, type: 'error' });
              }
            }
          });
        },
        handleChange: function (file, fileList) {
          // console.info('操作成功');
        },
        handleUploadSuccess: function (response, file, fileList) { // 上传成功
          var _self = this;
          if (response.data == '1') {
            _self.$message({
              duration: 4000,
              message: '流程id已经存在，修改文件flowId再上传',
              type: 'warning'
            });
          } else if (response.code == '500') {
            this.$message({ duration: 4000, message: '文件格式错误请检查', type: 'warning' });
          }
          _self.$refs.reftable.remoteData();
        },
        exportFn: function () { // 导出
          var _self = this;
          var selections = _self.$refs.reftable.selections;
          if (selections.length != 1) {
            _self.$message({
              duration: 4000,
              message: '请先选择一条记录',
              type: 'warning'
            });
            return;
          }
          var exportUrl = _self.urls.exportFlow + selections[0].flowId + '/' + selections[0].flowSign;
          yufp.util.download(exportUrl);
        },
        deleteFn: function () { // 删除
          var _self = this;
          var selections = _self.$refs.reftable.selections;
          if (selections.length !== 1) {
            _self.$message({
              duration: 4000,
              message: '请先选择要删除的记录',
              type: 'warning'
            });
            return;
          }
          if (selections[0].flowState == 'R') {
            _self.$message({
              duration: 4000,
              message: '启用的流程禁止删除',
              type: 'warning'
            });
            return;
          }
          _self.$confirm('确定要删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(function () {
            yufp.service.request({
              method: 'POST',
              url: _self.urls.batchdelete + selections[0].flowId + '/' + selections[0].flowSign,
              callback: function (code, message, response) {
                if (response.code == 0) {
                  _self.$refs.reftable.remoteData();
                  if (response.data == 0) {
                    _self.$message({
                      duration: 4000,
                      message: '有待办或办结的流程不允许删除',
                      type: 'warning'
                    });
                  } else {
                    _self.$message({
                      duration: 4000,
                      message: '成功删除' + response.data + '条记录',
                      type: 'success'
                    });
                  }
                } else {
                  _self.$message({
                    duration: 4000,
                    message: '删除异常:' + response.message,
                    type: 'error'
                  });
                }
              }
            });
          }).catch(function (e) { });
        },
        sureAdd: function () {
          var _self = this;
          _self.getdate();
          var formUrl = _self.urls.create;
          var param = {
            flowName: _self.editForm.newflowName,
            flowAdmin: _self.commonparams.CurrentuserId,
            orgId: yufp.session.org.code,
            systemId: 'cmis',
            startTime: _self.startTime
          };
          // 特殊字符校验
          var reg = new RegExp('[`~!@#$%^&*()=|{}\':;\',\\[\\].<>/?~！@#￥……&*（）|{}【】‘；：”“\'。，、？]');
          if (param.flowName && reg.test(param.flowName)) {
            _self.$message({ message: '包含特殊字符', type: 'warning' });
            return;
          }
          _self.$refs.newform.validate(function (valid) {
            if (valid) {
              yufp.service.request({
                method: 'POST',
                url: formUrl,
                data: param,
                callback: function (code, message, response) {
                  if (response.code === 0) {
                    _self.$refs.reftable.remoteData();
                    _self.$message('流程图新增成功!');
                    _self.newdialogVisible = false;
                  } else {
                    _self.$message({ duration: 4000, message: '新增异常:' + response.message, type: 'error' });
                  }
                }
              });
            }
          });
        },
        cancel: function () {
          var _self = this;
          _self.newdialogVisible = false;
          _self.$nextTick(function () {
            // _self.editForm.newflowName = '';
            _self.$refs.newform.resetFields();
          });
        },
        getdate: function () {
          var d = new Date();
          var year = d.getFullYear();
          var month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
          var date = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
          var hour = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
          var minutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
          var seconds = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();
          var myWant = year + '-' + month + '-' + date + ' ' + hour + ':' + minutes + ':' + seconds;
          this.startTime = myWant;
        },
		trackClose: function () {
		  this.trackDialogVisible = false;
		},
        saveAsNew: function () { // 保存为新版本
          var _self = this;
          var selections = _self.$refs.reftable.selections;
          if (selections.length !== 1) {
            _self.$message({
              duration: 4000,
              message: '请先选择一条记录',
              type: 'warning'
            });
            return;
          }
          var param = {
            'flowId': selections[0].flowId,
            'flowSign': selections[0].flowSign
          };
          _self.$confirm('确定要将流程:' + selections[0].flowName + ' 另存为新的版本吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(function () {
            yufp.service.request({
              method: 'POST',
              data: param,
              url: backend.workflowService + '/api/nwfflow/saveNew',
              callback: function (code, msg, response) {
                if (response.code == '500') {
                  _self.$message({ duration: 4000, message: '生成失败,请检查流程图配置', type: 'warning' });
                  _self.$refs.reftable.remoteData();
                }
                if (response.data) {
                  _self.$message('另存新版本流程图成功!');
                  _self.$refs.reftable.remoteData();
                }
              }
            });
          }).catch(function (e) { });
        }
      }
    });
  };
});
